package org.jeecg.modules.system.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.enums.common.DataScopeEnum;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.modules.system.model.TreeModel;
import org.jeecg.modules.system.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.util.FindsDepartsChildrenUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * @Description: 作用域管理
 * @Author: jeecg-boot
 * @Date:   2019-10-05
 * @Version: V1.0
 */
@Slf4j
@Api(tags="作用域管理")
@RestController
@RequestMapping("/b/sys/scope")
public class SysScopeController {
	@Autowired
	private ISysScopeService sysScopeService;
	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	private ISysScopeDepartService sysScopeDepartService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysUserRoleService sysUserRoleService;



	/**
	  * 分页列表查询
	 * @param sysScope
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "作用域管理-分页列表查询")
	@ApiOperation(value="作用域管理-分页列表查询", notes="作用域管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<SysScope>> queryPageList(SysScope sysScope,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<SysScope>> result = new Result<IPage<SysScope>>();
		LambdaQueryWrapper<SysScope> query = new LambdaQueryWrapper<SysScope>();
		if (StringUtils.isNotBlank(sysScope.getScopeName())){
			query.like(SysScope::getScopeName,sysScope.getScopeName().trim());
		}
		query.orderByAsc(SysScope::getScopeType);
		query.orderByDesc(SysScope::getUpdateTime);
		//改变排序的优先级顺序
//		QueryWrapper<SysScope> queryWrapper =  new QueryWrapper<>();
//		queryWrapper.orderByAsc("scope_type");
//		QueryGenerator.installMplus(queryWrapper,sysScope,req.getParameterMap(),true);
		Page<SysScope> page = new Page<SysScope>(pageNo, pageSize);
		IPage<SysScope> pageList = sysScopeService.page(page, query);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param sysScope
	 * @return
	 */
	@AutoLog(value = "作用域管理-添加")
	@ApiOperation(value="作用域管理-添加", notes="作用域管理-添加")
	@PostMapping(value = "/add")
	public Result<SysScope> add(@RequestBody SysScope sysScope) {
		Result<SysScope> result = new Result<SysScope>();
		try {
			List<SysScope> existList = sysScopeService.findByName(sysScope.getScopeName(),null);
			if (existList.size() >0){
				return Result.error("作用域名称重复,添加失败");
			}
			sysScopeService.save(sysScope);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param sysScope
	 * @return
	 */
	@AutoLog(value = "作用域管理-编辑")
	@ApiOperation(value="作用域管理-编辑", notes="作用域管理-编辑")
	@PutMapping(value = "/edit")
	public Result<SysScope> edit(@RequestBody SysScope sysScope) {
		try{
			SysScope sysScopeEntity = sysScopeService.getById(sysScope.getId());
			if(sysScopeEntity==null) {
				return Result.error("未找到对应实体");
			}
			List<SysScope> existList = sysScopeService.findByName(sysScope.getScopeName(),sysScopeEntity.getId());
			if (existList.size() >0){
				return Result.error("作用域名称重复,修改失败");
			}
			boolean ok = sysScopeService.updateById(sysScope);
			if(ok) {
				return Result.ok("修改成功!");
			}
			return Result.error("系统繁忙,修改失败!");
		}catch (Exception e){
			log.error(e.getMessage(),e);
			return Result.error("系统繁忙,处理失败!");
		}
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "作用域管理-通过id删除")
	@ApiOperation(value="作用域管理-通过id删除", notes="作用域管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			SysScope sysScope = sysScopeService.getById(id);
			if (sysScope != null && DataScopeEnum.DATA_SCOPE_TENANT_ADMIN.getCode() == sysScope.getScopeType()){
				return Result.error("系统管理员不可删除!");
			}
			sysScopeService.removeById(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "作用域管理-批量删除")
	@ApiOperation(value="作用域管理-批量删除", notes="作用域管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<SysScope> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		if(ids==null || "".equals(ids.trim())) {
			return Result.error("参数不识别！");
		}else {
			List<SysScope> sysScopeList = sysScopeService.getByIds(Arrays.asList(ids.split(",")));
			boolean adminFlg = false;
			for (SysScope sysScope:sysScopeList){
				if (sysScope.getScopeType() == DataScopeEnum.DATA_SCOPE_TENANT_ADMIN.getCode()){
					adminFlg = true;
					break;
				}
			}
			if (adminFlg){
				return Result.error("系统管理员不可删除!");
			}
			this.sysScopeService.removeByIds(Arrays.asList(ids.split(",")));
			return Result.ok("删除成功!");
		}
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "作用域管理-通过id查询")
	@ApiOperation(value="作用域管理-通过id查询", notes="作用域管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<SysScope> queryById(@RequestParam(name="id",required=true) String id) {
		Result<SysScope> result = new Result<SysScope>();
		SysScope sysScope = sysScopeService.getById(id);
		if(sysScope==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(sysScope);
			result.setSuccess(true);
		}
		return result;
	}


	 /**
	  * 作用域授权功能，查询菜单权限树
	  * @param request
	  * @return
	  */
	 @RequestMapping(value = "/queryAllDepartTreeList", method = RequestMethod.GET)
	 public Result<Map<String,Object>> queryAllDepartTreeList(HttpServletRequest request) {
		 Result<Map<String,Object>> result = new Result<>();
		 //全部权限ids
		 List<String> ids = new ArrayList<>();
		 try {
			 LoginUser user = SsoUtil.getLoginUser();
			 List<SysDepartTreeModel> departList = new ArrayList<>();
			Set<String> userTypes =  sysUserService.getUserRoleTypeSet(user.getId());
			//物业公司管理员 - 系统管理员
			if (userTypes.contains(DataScopeEnum.DATA_SCOPE_TENANT_ADMIN.getCode())){
				departList =  sysDepartService.queryTreeList();
			} else {
				List<SysDepart> departTreeList = sysUserRoleService.queryDepartTreeList("", SsoUtil.getLoginUser().getId(),"");
				departList = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(departTreeList);
			}
			 Map<String,Object> resMap = new HashMap<String,Object>();
			 getAllListId(departList,ids);
			 resMap.put("treeList", departList); //全部树节点数据
			 resMap.put("ids", ids);//全部树ids
			 result.setResult(resMap);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(), e.fillInStackTrace());
		 }
		 return result;
	 }

	 private void getAllListId(List<SysDepartTreeModel> departList,List<String> ids){
	 	if (ids == null){
	 		ids = new ArrayList<>();
		}
	 	for (SysDepartTreeModel depart : departList){
	 		ids.add(depart.getId());
	 		if (depart.getChildren() != null && depart.getChildren().size() > 0 ){
				getAllListId(depart.getChildren(),ids);
			}
		}
	 }

	 /**
	  * 查询作用域授权
	  *
	  * @return
	  */
	 @RequestMapping(value = "/queryScopeDepart", method = RequestMethod.GET)
	 public Result queryScopeDepart(@RequestParam(name = "scopeId", required = true) String scopeId) {
//		 Result<List<String>> result = new Result<>();
		 try {
			 List<SysScopeDepart> list = sysScopeDepartService.list(new QueryWrapper<SysScopeDepart>().lambda().eq(SysScopeDepart::getScopeId, scopeId));
			 List<String> departIds = new ArrayList<>();
			 List<String> halfDepartIds = new ArrayList<>();
			 for (SysScopeDepart temp:list){
			 	if (temp.getHalfStatus() == 1){
			 		departIds.add(temp.getDepartId());
				} else{
					halfDepartIds.add(temp.getDepartId());
				}
			 }
			 Map<String,List<String>> map = new HashMap<>();
			 map.put("departIds",departIds);
			 map.put("halfDepartIds",halfDepartIds);
//			 result.setResult(list.stream().map(SysScopeDepart -> String.valueOf(SysScopeDepart.getDepartId())).collect(Collectors.toList()));
			 return Result.ok(map);
		 } catch (Exception e) {
			 log.error(e.getMessage(), e);
			 return Result.error("系统繁忙，获取失败！");
		 }
//		 return result;
	 }

	 /**
	  * 保存作用域授权
	  *
	  * @return
	  */
	 @RequestMapping(value = "/saveScopeDepart", method = RequestMethod.POST)
	 //@RequiresRoles({ "admin" })
	 public Result<String> saveScopeDepart(@RequestBody JSONObject json) {
		 long start = System.currentTimeMillis();
		 Result<String> result = new Result<>();
		 try {
			 String scopeId = json.getString("scopeId");
			 String departIds = json.getString("departIds");
			 String lastDepartIds = json.getString("lastDepartIds");
			 String halfDepartIds = json.getString("halfDepartIds");
			 String halfLastDepartIds = json.getString("halfLastDepartIds");
			 this.sysScopeDepartService.saveScopeDepart(scopeId, departIds, lastDepartIds,1);
			 this.sysScopeDepartService.saveScopeDepart(scopeId, halfDepartIds, halfLastDepartIds,0);
			 result.success("保存成功！");
			 log.info("======作用域授权成功=====耗时:" + (System.currentTimeMillis() - start) + "毫秒");
		 } catch (Exception e) {
			 result.error500("授权失败！");
			 log.error(e.getMessage(), e);
		 }
		 return result;
	 }

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<SysScope> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              SysScope sysScope = JSON.parseObject(deString, SysScope.class);
              queryWrapper = QueryGenerator.initQueryWrapper(sysScope, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<SysScope> pageList = sysScopeService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "作用域管理列表");
      mv.addObject(NormalExcelConstants.CLASS, SysScope.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("作用域管理列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<SysScope> listSysScopes = ExcelImportUtil.importExcel(file.getInputStream(), SysScope.class, params);
              sysScopeService.saveBatch(listSysScopes);
              return Result.ok("文件导入成功！数据行数:" + listSysScopes.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
